﻿#include "workorder.h"
#include "qdebug.h"
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QDateTime>
#include <QSet>

WorkOrder::WorkOrder() {}

// 工单号配置
QString WorkOrder::getInfor(QString key, QString workPathTmp){
    if(workPathTmp.isEmpty()) workPathTmp=workPath;
    QDir dir(workPathTmp);
    if(!dir.exists()) return "";
    QSettings cfg(dir.absolutePath()+"/config.ini", QSettings::IniFormat);
    QString value=cfg.value(key, "").toString();
    return QString(value);
}
void WorkOrder::setInfor(QString key, QString data, QString workPathTmp){
    if(workPathTmp.isEmpty()) workPathTmp=workPath;
    QDir dir(workPathTmp);
    if(!dir.exists()) return;
    QSettings cfg(dir.absolutePath()+"/config.ini", QSettings::IniFormat);
    cfg.setValue(key, data);
}

// 设置工单号路径
void WorkOrder::setWorkPath(QString workPathTmp)
{
    if(workPathTmp.left(6)!="./btw/") workPathTmp="./btw/"+workPathTmp;
    workPath = workPathTmp;
}

// 获取工单号的数据
QVector<QStringList> WorkOrder::getData(QWidget *obj){
    QString filePath=workPath+"/print_all_data.txt";
    QVector<QStringList> all_str_list;
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        if(obj) QMessageBox::warning(obj, "错误", "数据文件打开失败!");
        return all_str_list; // 返回空的QList
    }
    QTextStream in(&file);
    QString line=in.readLine();
    // 获取第一行, 设置表头
    if(!in.atEnd()){
        QList<QString> strList = line.split(",");
        if(strList.size()<2){
            if(obj) QMessageBox::warning(obj, "错误", "文件格式错误!");
            file.close();
            return all_str_list;
        }
        all_str_list.push_back(strList);
    }
    // 后面的
    while (!in.atEnd()) {
        line = in.readLine(); // 读取一行
        QStringList strList = line.split(",");
        if(strList.size()==2){
            all_str_list.push_back(strList);
        }
    }
    file.close();
    return all_str_list;
}

// 搜索数据在某个工单号是否存在
bool WorkOrder::isInWorkOrder(QString str_search, QWidget *obj){
    QString filePath=workPath+"/print_all_data.txt";
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        if(obj) QMessageBox::warning(obj, "错误", "数据文件打开失败!");
        return false;
    }
    QTextStream in(&file);
    QString all_data=in.readAll();
    bool isIn = (-1!=all_data.indexOf(str_search));
    return isIn;
}

// 获取工单号列表
struct MyFileInfo{
    QString path;
    QDateTime t;
};

QStringList WorkOrder::getWorkList(){
    QVector<MyFileInfo> v_f_info;
    QDir dir("./btw");
    QString startPath = dir.path();
    QDirIterator it(startPath, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        it.next();
        QFileInfo info = it.fileInfo();
        if(info.isDir()){
        }else{
            if(info.fileName()=="print_all_data.txt"){
                v_f_info.push_back({info.path(), info.created()});
            }
        }
    }
    // 2024年8月21日添加工单号创建日期的配置进行排序
    for (const auto &f_info : v_f_info) {
        QString conf_str = getInfor("create_time", f_info.path);
        if(conf_str.isEmpty()){
            setInfor("create_time", QString::number(f_info.t.toTime_t()), f_info.path);
        }else{
            f_info.t.fromTime_t(conf_str.toUInt());
        }
    }
    // Sort directories by creation time
    std::sort(v_f_info.begin(), v_f_info.end(), [](const MyFileInfo &a, const MyFileInfo &b) {
        return a.t > b.t;
    });
    QStringList str_list;
    // Add sorted directories to the list
    for (const auto &f_info : v_f_info) {
        QString path=f_info.path;
        path.replace(dir.path()+"/", "");
        str_list.push_back(path);
    }
    return str_list;
}

// 保存打印记录（防止重复打印用）
void WorkOrder::log(QString fileName, const QSet<int> &data){
    QDir dir(workPath);
    if(!dir.exists()||data.empty()) return;
    QFile file(dir.absolutePath()+"/"+fileName);
    if (!file.open(QIODevice::WriteOnly)) {
        return;
    }
    QDataStream out(&file);
    out.setVersion(QDataStream::Qt_5_14);
    out << data;
    file.close();
}

QSet<int> WorkOrder::getLog(QString fileName){
    QSet<int> data;
    QDir dir(workPath);
    if(!dir.exists()) return data;
    QFile file(dir.absolutePath()+"/"+fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        return data;
    }
    QDataStream in(&file);
    in.setVersion(QDataStream::Qt_5_14);
    in >> data;
    file.close();
    return data;
}

bool WorkOrder::isInLog(QString fileName, int row){
    QSet<int> data = getLog(fileName);
    return (data.contains(row));
}
